package com.cskaoyan.processor;

import com.cskaoyan.util.ProxyUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author stone
 * @date 2022/12/20 16:24
 */
@Component
public class ServiceProxyPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.contains("Service")) {

            // Object invoke = method.invoke(t, objects);
            // 如果传入的是1 → t clazz.newInstance(); → 新的实例 → component1 为 null
            // 如果传入的是2 → t bean → 经过了生命周期的一些流程之后的bean → component1不为null

            // 传入的是正在生命周期的组件的Class
            return ProxyUtil.getServiceProxy(bean.getClass());//1
            // 传入的是正在生命周期的组件
            //return ProxyUtil.getServiceProxy(bean); //2 √
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
